package com.itheima.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.pojo.Result;
import com.itheima.pojo.StatusCode;
import com.itheima.pojo.TodoVO;
import com.itheima.service.TodoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/todo")
public class TodoController {

    @Autowired
    private TodoService todoService;

    /**
     * 添加
     * @param todoVO
     */
    @PostMapping("/add")
    public Result add(@RequestBody TodoVO todoVO) {

        try {
            todoService.add(todoVO);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(StatusCode.ERROR,"插入失败");
        }
        //封装返回数据
        return new Result(StatusCode.OK,"插入成功");
    }

    /**
     * 删除
     * @param todoVO
     */
    @PostMapping("/delete")
    public Result delete(@RequestBody TodoVO todoVO){

        try {
            todoService.delete(todoVO);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(StatusCode.ERROR,"删除失败");
        }
        //封装返回数据
        return new Result(StatusCode.OK,"删除成功");
    }

    /**
     * 编辑
     * @param todoVO
     */
    @PostMapping("/edit")
    public Result edit(@RequestBody TodoVO todoVO){

        try {
            todoService.edit(todoVO);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(StatusCode.ERROR,"更新失败");
        }
        //封装返回数据
        return new Result(StatusCode.OK,"更新成功");
    }

    /**
     * 条件+分页查询
     * @param todoVO
     * @return
     */
    @PostMapping("/getList")
    public Map<String,Object> getList(@RequestBody TodoVO todoVO){
        PageInfo pageInfo = todoService.getList(todoVO);
        //封装返回数据
        Map<String,Object> result=new HashMap<>();

        Map<String,Object> datas=new HashMap<>();
        datas.put("records",pageInfo.getList());
        datas.put("total",pageInfo.getTotal());
        datas.put("size",pageInfo.getSize());
        datas.put("current",pageInfo.getPageNum());
        datas.put("orders","");
        datas.put("optimizeCountSql",true);
        datas.put("isSearchCount",true);

        //将将data放入返回map
        result.put("code","success");
        //封装data
        result.put("data",datas);
        return  result;
    }
}
